﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.IO;
using System.Runtime.InteropServices;
using System.Diagnostics;
using KC.DataAccess.Processor;

namespace KC.Business.Processor.Plugins.JobProcessors
{
	public class DiskPingerProcessor : ProcessorBase
	{
		public override bool Run()
		{
			foreach (DiskPingerShare share in dc.DiskPingerShares)
			{
				ProcessStartInfo psi = new ProcessStartInfo("net.exe", "use " + share.UncPath + " " + share.Password + " /USER:" + share.Username);
				psi.RedirectStandardError = true;
				psi.RedirectStandardInput = false;
				psi.RedirectStandardOutput = true;
				psi.UseShellExecute = false;
				psi.CreateNoWindow = true;
				psi.ErrorDialog = false;

				// oh, this one's a simple string. How 'bout that.
				psi.UserName = System.Configuration.ConfigurationManager.AppSettings["processUsername"];

				// fucking bullshit, right here. No reason I shouldn't be able to give it a network credential object or something. Somebody got their name on a powerpoint slide for this one.
				psi.Password = new System.Security.SecureString();
				psi.Password.Clear();
				foreach (char str in System.Configuration.ConfigurationManager.AppSettings["processPassword"])
					psi.Password.AppendChar(str);

				Process p = Process.Start(psi);
				
				string output = "", err = "";
				try {
					err = p.StandardError.ReadToEnd();
					output = p.StandardOutput.ReadToEnd(); 
				}
				catch (Exception ex) { 
					LogError(ex);
					return false; }
				p.WaitForExit();

				string detail = "EXECUTE \"" + psi.FileName + " " + psi.Arguments.Replace(System.Configuration.ConfigurationManager.AppSettings["processPassword"], "[PASSWORD REDACTED]") + "\" - Result: ";

				if (!string.IsNullOrEmpty(err)) detail += err;
				if (!string.IsNullOrEmpty(output)) detail += output;
				AddDetail(detail);
				if (!string.IsNullOrEmpty(err))
					LogError(err);
			}


			return true;
		}
	}
}
